<template>
  <el-form
    size="mini"
    ref="isfform"
    :model="form"
    :rules="rules"
    label-position="left"
    label-width="100px"
    v-loading.fullscreen.lock="loading"
  >
    <el-card>
      <div slot="header" class="clearfix relative small-header">
        <el-row>
          <el-col :span="2" :offset="0">
            <div class="title-icon">
              <span>ISF申报</span>
            </div>
          </el-col>
          <el-col :span="2">
            <a
              class="text-blue"
              href="http://www.bingfms.com/User/Login"
              target="_blank"
              >海关申报系统</a
            >
          </el-col>
          <el-col :span="4" :offset="0">
            <!-- <el-form-item prop="isfManifestTypeCode"> -->
            <el-radio-group v-model="form.isfManifestTypeCode">
              <el-radio :label="parseInt(1)"> ISF-10 </el-radio>
              <el-radio :label="parseInt(2)"> ISF-05 </el-radio>
            </el-radio-group>
            <!-- </el-form-item> -->
          </el-col>

          <el-col
            :span="16"
            class="text-right"
            v-if="!(waybillData.isf && waybillData.isf >= 1)"
          >
            <el-button
              size="mini"
              type="success"
              @click="checkForm('updateIsfDeclare')"
              >保存</el-button
            >
            <el-button size="mini" @click="checkForm('isfDeclare')"
              >申报</el-button
            >
          </el-col>
        </el-row>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="SCAC:" prop="scacCode">
            <el-input v-model="form.scacCode" maxlength="4"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item prop="masterBlType" label="提单类型">
            <el-select v-model="form.masterBlType" filterable>
              <el-option
                v-for="(v, i) in masterBlType"
                :key="i"
                :label="`${i} | ${v}`"
                :value="i"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            prop="customsEntryType"
            label="进口报关类型"
            class="text-red"
            v-if="form.isfManifestTypeCode === 2"
          >
            <el-select v-model="form.customsEntryType" filterable>
              <el-option
                v-for="(v, i) in customsEntryType"
                :key="i"
                :label="`${i} | ${v}`"
                :value="i"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!--购买方式和类型ISF05和ISF10申报均需要-->
        <el-col :span="8">
          <el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="14" :xl="14">
              <el-form-item prop="bondType" label="购买方式-类型:">
                <el-select v-model="form.bondType" filterable>
                  <el-option
                    v-for="(v, i) in bondType"
                    :key="i"
                    :label="`${i} | ${v}`"
                    :value="parseInt(i)"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="10" :xl="10">
              <el-form-item prop="bondActivityCode" label-width="0">
                <el-select v-model="form.bondActivityCode" filterable>
                  <el-option
                    v-for="(v, i) in bondActivityCode"
                    :key="i"
                    :label="`${i} | ${v}`"
                    :value="i"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="8">
          <!--持有人类型ISF05和ISF10申报均需要-->

          <el-form-item prop="bondHolderType" label="持有人类型:">
            <el-select v-model="form.bondHolderType" filterable>
              <el-option
                v-for="(v, i) in bondHolderType"
                :key="i"
                :label="`${i} | ${v}`"
                :value="i"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!--持有人类型ISF05和ISF10申报均需要 与进口商和订舱方信息相关无需自己填写，系统自动带出-->
        <el-col :span="8">
          <el-form-item label="关联号:" prop="bondReferenceNo">
            <el-input v-model="form.bondReferenceNo"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!--订舱信息/进口商信息/收发件人-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item
            prop="isfImporter"
            class="text-red"
            :label="form.isfManifestTypeCode === 1 ? '进口商' : '订舱方'"
          >
            <!-- <div slot="label" class="text-red">
              {{ form.isfManifestTypeCode === 1 ? '进口商' : '订舱方' }}:
            </div> -->
            <div>
              <el-select
                v-model="form.isfImporter"
                @change="declareCustomer($event, 'isfImporter')"
                filterable
              >
                <el-option
                  v-for="(v, i) in restaurants"
                  :key="i"
                  :label="v"
                  :value="parseInt(i)"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <InfoCard
            v-if="showisfImporter"
            :info="isfImporter"
            class="margin-bottom"
          />
        </el-col>
        <el-col :span="8">
          <el-form-item prop="isfShipper" label="发件人:">
            <el-select
              v-model="form.isfShipper"
              filterable
              placeholder="请选择发件人"
              @change="declareCustomer($event, 'isfShipper')"
            >
              <el-option
                v-for="(v, i) in restaurants"
                :key="i"
                :label="v"
                :value="parseInt(i)"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <InfoCard v-if="showisfShipper" :info="isfShipper" />
        </el-col>
        <el-col :span="8">
          <el-form-item prop="isfConsignee" label="收件人">
            <div>
              <el-select
                v-model="form.isfConsignee"
                filterable
                placeholder="请选择收件人"
                @change="declareCustomer($event, 'isfConsignee')"
              >
                <el-option
                  v-for="(v, i) in restaurants"
                  :key="i"
                  :label="v"
                  :value="parseInt(i)"
                >
                </el-option>
              </el-select>
            </div>
          </el-form-item>
          <InfoCard v-if="showisfConsignee" :info="isfConsignee" />
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item prop="hsCodes">
            <div slot="label">
              海关Hts：
              <span class="text-red">*</span>
              <i
                class="
                      el-icon-circle-plus
                      text-green 
                      text-xl
                      margin-left-sm
                    "
                @click="addCustomsCode"
              />
            </div>
            <el-row :gutter="0">
              <el-col
                v-for="(item, index) in form.hsCodesList"
                :key="`hsCodes${index}`"
                class="flex margin-bottom-sm align-center"
                :span="4"
              >
                <el-input
                  v-model="item.hsCodes"
                  clearable
                  maxlength="15"
                  placeholder="默认原产国为中国"
                />
                <!-- <div class="flex align-center justify-start"> -->

                <i
                  class="el-icon-remove text-xl margin-lr-sm  text-red"
                  @click="removeCustomsCode(index)"
                />
                <!-- </div> -->
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog title="特别说明" :visible.sync="showDialog" width="50%">
      <div>
        <p>ISF-10申报，我们将会用发件人作为集装箱供应商</p>
        <p>
          集装箱的装柜地址：默认为SHENZHEN JIUFANG E-COMMERCE LOGISTICS LIMITED
        </p>
        <p>
          拼箱的公司名称和地址：默认为SHENZHEN JIUFANG E-COMMERCE LOGISTICS
          LIMITED
        </p>
        <p>买方的名称和地址：我们将会用收件人地址信息</p>
        <p>美国收货人的美国保税号码：我们将会用收件人地址信息</p>
        <p>货物送达的公司名称和地址：我们将会用收件人地址信息</p>
        <p>海关编码原产国默认为中国</p>
        <p class="text-red text-bold">系统提交成功以后请去申报系统进行核实。</p>
        <p>
          如果您对此有疑问请放弃此申报去<a
            class="text-blue"
            href="http://www.bingfms.com/User/Login"
            target="_blank"
            >http://www.bingfms.com/User/Login系统进行申报</a
          >
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="showDialog = false">取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          :disabled="count ? true : false"
          @click="isfDeclare"
        >
          {{ count ? `确 定(${count})` : "确 定" }}
        </el-button>
      </span>
    </el-dialog>
  </el-form>
</template>

<script>
import { ajax } from "@/store/yg/common/utils";
import InfoCard from "./InfoCard";
export default {
  props: {
    restaurants: {
      type: Object,
      default: function() {
        return {};
      }
    },
    waybillData: {
      type: Object,
      default: function() {
        return {};
      }
    }
  },
  components: {
    InfoCard
  },
  data() {
    return {
      loading: false,
      count: 0,
      timer: null,
      bondType: {
        8: "Continuous",
        9: "Single Transaction"
      },
      masterBlType: {
        BM: "Bill of Lading Number",
        OB: "Ocean Bill of Lading"
      },
      bondActivityCode: {
        "01": "Importer or Broker",
        "02": "Custodian of Bonded Merchandise",
        "03": "International Carrier",
        "04": "Foreign Trade Zone Operator",
        "16": "ISF Bond"
      },
      bondHolderType: {
        ANI: "Customs and Border Protection CBP assigned Importer Identifier",
        EI: "Employers Identification Number",
        SY: "Social Security Number"
      },
      customsEntryType: {
        "00": "Freight Remains On Board FROB",
        "62": "Transportation Exportation",
        "63": "Immediate Exportation"
      },
      isfShipper: {},
      isfConsignee: {},
      isfImporter: {},
      showDialog: false,
      showisfShipper: false,
      showisfConsignee: false,
      showisfImporter: false,
      form: {
        id: "",
        scacCode: "",
        isfManifestTypeCode: 1,
        isfShipper: "",
        isfConsignee: "",
        isfImporter: "",
        hsCodesList: [{ hsCodes: "" }],
        hsCodes: [],
        bondType: "",
        bondActivityCode: "",
        bondHolderType: "",
        customsEntryType: "",
        bondReferenceNo: "",
        masterBlType: ""
      },
      rules: {
        scacCode: [{ required: true, message: "请填写", trigger: "blur" }],
        masterBlType: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        bondType: [{ required: true, message: "请选择", trigger: "change" }],
        bondActivityCode: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        bondHolderType: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        customsEntryType: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        bondReferenceNo: [
          { required: true, message: "请填写", trigger: "blur" }
        ],
        isfShipper: [{ required: true, message: "请选择", trigger: "change" }],
        isfConsignee: [
          { required: true, message: "请选择", trigger: "change" }
        ],
        isfImporter: [{ required: true, message: "请选择", trigger: "change" }]
      }
    };
  },
  watch: {
    "form.hsCodesList": {
      handler(newValue, oldValue) {
        let arr = [];
        for (const i of this.form.hsCodesList) {
          if (i.hsCodes) {
            arr.push(i.hsCodes);
          }
        }
        this.form.hsCodes = arr;
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    if (this.waybillData.scacCode) {
      this.form.scacCode = this.waybillData.scacCode;
    }
    if (this.waybillData.isfManifestTypeCode) {
      this.form.isfManifestTypeCode = this.waybillData.isfManifestTypeCode;
    }
    if (this.waybillData.isfShipper) {
      this.form.isfShipper = this.waybillData.isfShipper;
      this.declareCustomer(this.form.isfShipper, "isfShipper");
    }
    if (this.waybillData.isfConsignee) {
      this.form.isfConsignee = this.waybillData.isfConsignee;
      this.declareCustomer(this.form.isfConsignee, "isfConsignee");
    }
    if (this.waybillData.isfImporter) {
      this.form.isfImporter = this.waybillData.isfImporter;
      this.declareCustomer(this.form.isfImporter, "isfImporter");
    }
    if (this.waybillData.bondType) {
      this.form.bondType = this.waybillData.bondType;
    }
    if (this.waybillData.bondActivityCode) {
      this.form.bondActivityCode = this.waybillData.bondActivityCode;
    }
    if (this.waybillData.bondHolderType) {
      this.form.bondHolderType = this.waybillData.bondHolderType;
    }
    if (this.waybillData.customsEntryType) {
      this.form.customsEntryType = this.waybillData.customsEntryType;
    }
    if (this.waybillData.bondReferenceNo) {
      this.form.bondReferenceNo = this.waybillData.bondReferenceNo;
    }
    if (this.waybillData.masterBlType) {
      this.form.masterBlType = this.waybillData.masterBlType;
    }
    if (this.waybillData.hsCodes.length > 0) {
      let arr = [];
      for (const i of this.waybillData.hsCodes) {
        arr.push({ hsCodes: i });
      }
      this.form.hsCodesList = arr;
    }
  },
  methods: {
    async updateIsfDeclare() {
      this.loading = true;
      this.form.id = this.waybillData.id;
      console.log("this.form :>> ", this.form);
      const { code, message } = await ajax("updateIsfDeclare", this.form);
      this.loading = false
      if (code !== 200) {
        this.$message.error(message | "保存失败");
        return;
      }
      this.$message.success("保存成功");
    },
    checkForm(name) {
      if (!this.form.isfManifestTypeCode) {
        this.$message.error("请选择ISF-10 或者 ISF-5");
        return;
      }
      this.$refs.isfform.validate(valid => {
        if (valid) {
          if (this.form.hsCodes.length === 0) {
            this.$message.error("请填写海关编码");
            return;
          }

          if (name === "updateIsfDeclare") {
            this.updateIsfDeclare();
          }
          if (name === "isfDeclare") {
            // this.isfDeclare()
            this.showDialog = true;

            const TIME_COUNT = 15;
            if (!this.timer) {
              this.count = TIME_COUNT;
              // this.showCount = false
              this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                  this.count--;
                } else {
                  clearInterval(this.timer);
                  this.timer = null;
                }
              }, 1000);
            }
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    async isfDeclare() {
      
      this.loading = true;
      const { code, message } = await ajax("isfDeclare", {
        id: this.waybillData.id
      });
      this.loading = false;
      if (code !== 200) {
        this.$message.error(message || "申报失败");
        return;
      }
      this.$message.success("申报成功");
      this.showDialog = false;
    },
    async declareCustomer(id, type) {
      this.form[type] = id;
      console.log("this.form :>> ", this.form);
      this.loading = true;
      const { code, data, message } = await ajax("declareCustomer", {
        id: id
      });
      this.loading = false;
      if (code !== 200) {
        this.$message.error(message || "获取数据失败");
        return;
      }
      this[`show${type}`] = true;
      this[type] = data;

      // 选择订舱服务商的时候
      // 将订舱服务商的 eiNo，syNo，aniNo赋值给关联号
      if ("isfImporter" === type) {
        if (data.eiNo) {
          this.form.bondHolderType = "EI";
          this.form.bondReferenceNo = data.eiNo;
        } else if (data.aniNo) {
          this.form.bondHolderType = "ANI";
          this.form.bondReferenceNo = data.aniNo;
        } else if (data.syNo) {
          this.form.bondHolderType = "SY";
          this.form.bondReferenceNo = data.syNo;
        }
      }
    },
    removeCustomsCode(index) {
      if (this.form.hsCodesList.length === 1) return;
      this.form.hsCodesList.splice(index, 1);
    },
    addCustomsCode(index) {
      // this.form.hsCodesList.splice(index + 1, 0, { hsCodes: "" });
      this.form.hsCodesList.push({ hsCodes: "" });
    }
  }
};
</script>

<style scoped>
/deep/ .el-select {
  width: 100%;
}

/deep/ .text-red .el-form-item__label {
  color: red !important;
}
</style>
